var config = require('config.js')
var http = require('./utils/httpHelper.js')
App({
  getUserInfo:function(cb){
    var that = this;
    if (this.globalData.userInfo!=null) {
      typeof cb == "function" && cb(this.globalData.userInfo)
    }else {
      //调用登录接口
      wx.login({
        success: function(resLogin) {
          if (resLogin.code) {
            var code = resLogin.code;
            wx.getUserInfo({
              success: function (resUser) {
                that.globalData.userInfo = resUser.userInfo;
                var data = {code:code, appid:config.APPID}
                http.httpGet(config.clubApi.putOpenid,data,function(resOpen, err){
                  if (resOpen.data.userId) {
                    that.setUserInfo(resOpen.data);
                  }else {
                    let openId = resOpen.data.openid;
                    that.queryUser(openId);
                  }
                });
                typeof cb == "function" && cb(that.globalData.userInfo)
              }
            });
          }else {
            console.log('获取用户登录态失败！' + res.errMsg)
          }
        }
      });
    }
  },
  queryUser:function(openId){
    var that = this
    http.httpGet(config.clubApi.wxUser,{
      openId:openId
    },function (res){
      if (res.data) {
        that.setUserInfo(res.data);
      }else {
        wx.setStorageSync('user', null);
        wx.setStorageSync('address', null);
      }
    });
  },
  setUserInfo(obj) {
    var that = this;
    that.globalData.userInfo = {};
    that.globalData.userInfo.userId = obj.userId;
    that.globalData.userInfo.userName = obj.userName;
    that.globalData.userInfo.avatar = obj.avatar;
    that.globalData.userInfo.phonenumber = obj.phonenumber;
    that.globalData.userInfo.sex = obj.sex;
    that.globalData.userInfo.token = obj.token;
    wx.setStorageSync('user', that.globalData.userInfo);
    wx.setStorageSync('address', obj.allAddress);
  },
  globalData:{
    userInfo:null
  }
})